# Create your views here.
from AppBase.base import  *
from django.views import View
from MallApp import models
from django.http import  FileResponse
from django.core.files import File
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import  random
from dateutil.relativedelta import relativedelta
from  MallApp.ALiPayMoney import PayMoney2
# 主页
# @method_decorator(checkLogin, name='dispatch')#添加需先登录的装饰器
class IndexView(View): #继承View类 统一视图入口 get和post等请求统一处理
    def get(self, request):
        # 统一返回全部数据  分页交由前端框架处理
        return render(request, 'MallApp/index.html')  # 主页

    def post(self, request):
        typename = request.POST.get("typename", "")
        searchName = request.POST.get("searchName", "")
        minid = int(request.POST.get('curPage', 1))
        pagesize = request.POST.get('pageSize', 10)

        DataItems = models.ResourceRecord.objects.filter(Q(Title__contains=searchName)).order_by("-HotValue")
        pagInator = Paginator(DataItems, pagesize)  # 数据分页处理
        currPage = pagInator.page(minid)  # 获取前端传入的第几页数据
        # 当前页的所有数据
        dataList = currPage.object_list
        data = []
        for itemData in dataList:
            data.append(
                {"ID": itemData.ID, "Title": itemData.Title, "Abstract": itemData.Abstract,
                 "CoverChart": itemData.CoverChart.url, "Content": itemData.Content,
                 "RecType": itemData.RecType.Name, "SourceFile": itemData.SourceFile.url,
                 "HotValue": itemData.HotValue, "UserId": itemData.Creator.id,
                 "UserName": itemData.Creator.username, "UserImage": itemData.Creator.img.url,
                 "CreateDatetime": timeConverStr(itemData.CreateDatetime)})
        return successResponseCommon(
            {"items": data, "pages": 1, "curpage": 1,
             "sumNum": len(DataItems),
             "nodataflag": 1})
#数据类型
class DataTypeView(View):
    def get(self, request):
        DataItems=models.ResourceTypeDict.objects.all()
        data = []
        for item in DataItems:
            data.append({"ID": item.ID, "Name": item.Name})
        return successResponseCommon(
            {"items": data, "pages": 1, "curpage": 1,
             "sumNum": len(DataItems),
             "nodataflag": 1})



#充值
@method_decorator(checkLogin, name='dispatch')
class PayMoneyView(View):
    def get(self, request):
        # 统一返回全部数据  分页交由前端框架处理
        return render(request, 'MallApp/pay_money.html')  # 主页
    def post(self,request):
        PayMoney = float(request.POST.get("money", 0))
        PayType=int(request.POST.get("type", 0))
        #获取当前用户会员到期日
        plusEndDate=request.user.plusEndDate
        if plusEndDate=="":
            plusEndDate=datetime.now().strftime("%Y-%m-%d")
        sdate = datetime.strptime(plusEndDate, '%Y-%m-%d')
        if PayType==0:
            delta =  relativedelta(months=1)
        elif PayType==1:
            delta = relativedelta(years=1)
        elif PayType == 2:
            delta = relativedelta(years=3)
        elif PayType == 3:
            delta = relativedelta(years=5)
        plusEndDate=(sdate + delta).strftime("%Y-%m-%d")
        # user=UserDict.objects.get(id=request.user.id)
        # user.plusEndDate=plusEndDate
        # user.save()

        order=models.UserPayRecord.objects.create(PayMoney=PayMoney,Creator=request.user)
        price=str(PayMoney)
        order_id=order.ID
        returnsuccessurl = request._current_scheme_host + "/mall/pay_success?plusEndDate=%s&id=%s&orderId=%s" % (
        plusEndDate, request.user.id,order_id)
        pay_url=PayMoney2(price,order_id,returnsuccessurl)
        return successResponseCommon({"pay_url":pay_url},"ok")


class PaySuccessView(View):
    def get(self,request):
        plusEndDate=request.GET.get("plusEndDate","")
        id=request.GET.get("id",0)
        orderId=request.GET.get("orderId",0)
        if id==0 or plusEndDate=="":
            return HttpResponse("充值失败！")
        UserPayRecorditem=models.UserPayRecord.objects.filter(Q(ID=orderId)&Q(status="0"))
        if len(UserPayRecorditem)<=0:
            return HttpResponse("充值失败！")
        UserPayRecorditem.update(status="1")
        user = UserDict.objects.get(id=id)
        user.plusEndDate = plusEndDate
        user.save()
        return redirect("/mall/pay_money")


#上传数据
@method_decorator(checkLogin, name='dispatch')
class UploadDataView(View):
    def get(self, request):
        return render(request, 'MallApp/upload_data.html')  # 上传数据页面
    def post(self,request):
        #保存上传的图片到数据库以及数据
        Title = request.POST.get('Title', '')
        Abstract = request.POST.get('Abstract', '')
        Content = request.POST.get('Content', '')
        RecType = request.POST.get('RecType', '')
        if RecType=="":
            return errorResponseCommon({}, "未选择数据类型")
        RecType=models.ResourceTypeDict.objects.get(Name=RecType)
        if request.FILES:
            SourceFile=request.FILES.get("datafile","")
            if SourceFile=="":
                return errorResponseCommon({}, "未上传数据文件")
            #遍历多个图片
            ImagesFiles = request.FILES.getlist("imagefile", [])
            if len(ImagesFiles)<=0:
                return errorResponseCommon({}, "未上传介绍图片")
            else:
                CoverChart=ImagesFiles[0]
            ResourceRec=models.ResourceRecord.objects.create(Title=Title,Abstract=Abstract,Content=Content,
                                                 CoverChart=CoverChart,SourceFile=SourceFile,RecType=RecType,
                                                 Creator=request.user)
            for image in ImagesFiles:
                models.ResourcePic.objects.create(ResourceRec=ResourceRec,Pic=image)
            return successResponseCommon({}, "ok")
        else:
            return errorResponseCommon({}, "未上传介绍图片")


#我的数据
@method_decorator(checkLogin, name='dispatch')
class MyDataView(View):
    def get(self,request):
        return render(request, 'MallApp/my_data.html')
    def post(self,request):
        typename = request.GET.get("typename", "")
        searchName = request.POST.get("searchName", "")
        minid = int(request.POST.get('curPage', 1))
        pagesize = request.POST.get('pageSize', 10)

        DataItems = models.ResourceRecord.objects.filter(Q(Title__contains=searchName) & Q(Creator=request.user))
        pagInator = Paginator(DataItems, pagesize)  # 数据分页处理
        currPage = pagInator.page(minid)  # 获取前端传入的第几页数据
        # 当前页的所有数据
        dataList = currPage.object_list
        data = []
        for itemData in dataList:
            data.append(
                {"ID": itemData.ID, "Title": itemData.Title, "Abstract": itemData.Abstract,
                "CoverChart": itemData.CoverChart.url,"Content":itemData.Content,
                 "RecType":itemData.RecType.Name,"SourceFile":itemData.SourceFile.url,
                 "HotValue": itemData.HotValue, "UserId": itemData.Creator.id,
                 "UserName":itemData.Creator.username,"UserImage": itemData.Creator.img.url,
                 "CreateDatetime": timeConverStr(itemData.CreateDatetime)})
        return successResponseCommon(
            {"items": data, "pages": 1, "curpage": 1,
             "sumNum": len(DataItems),
             "nodataflag": 1})


#数据详情页
@method_decorator(checkLogin, name='dispatch')
class DataDetailView(View):
    def get(self, request):
        id = request.GET.get("id", 0)
        return render(request, 'MallApp/data_detail.html',{"id":id})

    def post(self, request):
        id = request.POST.get("id", "")
        #获取数据记录
        itemData=models.ResourceRecord.objects.get(ID=id)
        #获取数据图片
        ImageDataItems = models.ResourcePic.objects.filter(Q(ResourceRec=itemData))
        data=[]
        data.append(
            {"ID": itemData.ID, "Title": itemData.Title, "Abstract": itemData.Abstract,
             "CoverChart": itemData.CoverChart.url, "Content": itemData.Content,
             "RecType": itemData.RecType.Name, "SourceFile": itemData.SourceFile.url,
             "HotValue": itemData.HotValue, "UserId": itemData.Creator.id,
             "UserName": itemData.Creator.username, "UserImage": itemData.Creator.img.url,
             "CreateDatetime": timeConverStr(itemData.CreateDatetime)})
        imageData=[]
        for item in ImageDataItems:
            imageData.append({"id":item.ID,"PicUrl":item.Pic.url})

         #同类推荐资源
        TJItems=models.ResourceRecord.objects.filter(Q(RecType=itemData.RecType) & ~Q(ID=id)).order_by("-HotValue")[:5]
        TJData=[]
        for itemData in TJItems:
            TJData.append(
                {"ID": itemData.ID, "Title": itemData.Title, "Abstract": itemData.Abstract,
                 "CoverChart": itemData.CoverChart.url, "Content": itemData.Content,
                 "RecType": itemData.RecType.Name, "SourceFile": itemData.SourceFile.url,
                 "HotValue": itemData.HotValue, "UserId": itemData.Creator.id,
                 "UserName": itemData.Creator.username, "UserImage": itemData.Creator.img.url,
                 "CreateDatetime": timeConverStr(itemData.CreateDatetime)})
        return successResponseCommon(
            {"items": data,"imageitems":imageData, "pages": 1, "curpage": 1,
             "sumNum": len(imageData),"TJData":TJData,
             "nodataflag": 1})


#数据下载
@method_decorator(checkLogin, name='dispatch')
class DownLoadDataView(View):
    def get(self, request):
        id = int(request.GET.get('id', 0))
        baseurl=request._current_scheme_host
        ResourceRec=models.ResourceRecord.objects.get(ID=id)
        # 判断资源是否是自己的
        if ResourceRec.Creator==request.user:
            ResourceRec.HotValue=ResourceRec.HotValue+1
            ResourceRec.save()
            return successResponseCommon({"url": baseurl+ResourceRec.SourceFile.url}, "ok")

        #首先判断用户是否下载过该资源
        DownLoadData=models.UserDownLoadRecord.objects.filter(Q(Creator=request.user) & Q(ResourceRec=ResourceRec))
        if len(DownLoadData)>0:
            ResourceRec.HotValue = ResourceRec.HotValue + 1
            ResourceRec.save()
            return successResponseCommon({"url": baseurl+ResourceRec.SourceFile.url}, "ok")

        #判断用户是否是会员有效期
        plusEndDate=request.user.plusEndDate
        if plusEndDate != "":
            #plusEndDate=strConverDate(plusEndDate)
            d_time1 = datetime.strptime(plusEndDate + " 23:59", '%Y-%m-%d %H:%M')
            n_time = datetime.now()
            if n_time <= d_time1:
                #写入下载记录
                models.UserDownLoadRecord.objects.create(ResourceRec=ResourceRec,Creator=request.user)
                ResourceRec.HotValue = ResourceRec.HotValue + 1
                ResourceRec.save()
                return successResponseCommon({"url":baseurl+ResourceRec.SourceFile.url}, "ok")

        #判断用户是否下载过3次
        DownLoadData=models.UserDownLoadRecord.objects.filter(Q(Creator=request.user))
        if len(DownLoadData)<3:
            # 写入下载记录
            models.UserDownLoadRecord.objects.create(ResourceRec=ResourceRec, Creator=request.user)
            ResourceRec.HotValue = ResourceRec.HotValue + 1
            ResourceRec.save()
            return successResponseCommon({"url": baseurl+ResourceRec.SourceFile.url}, "ok")

        return errorResponseCommon({},"需充值会员")

#我下载的数据
@method_decorator(checkLogin, name='dispatch')
class MyDownLoadDataView(View):
    def get(self, request):
        return render(request, 'MallApp/my_download.html')

    def post(self, request):
        typename = request.GET.get("typename", "")
        searchName = request.POST.get("searchName", "")
        minid = int(request.POST.get('curPage', 1))
        pagesize = request.POST.get('pageSize', 10)

        DataItems = models.UserDownLoadRecord.objects.filter(Q(Creator=request.user))
        pagInator = Paginator(DataItems, pagesize)  # 数据分页处理
        currPage = pagInator.page(minid)  # 获取前端传入的第几页数据
        # 当前页的所有数据
        dataList = currPage.object_list
        data = []
        for itemData in dataList:
            itemData=itemData.ResourceRec
            data.append(
                {"ID": itemData.ID, "Title": itemData.Title, "Abstract": itemData.Abstract,
                 "CoverChart": itemData.CoverChart.url, "Content": itemData.Content,
                 "RecType": itemData.RecType.Name, "SourceFile": itemData.SourceFile.url,
                 "HotValue": itemData.HotValue, "UserId": itemData.Creator.id,
                 "UserName": itemData.Creator.username, "UserImage": itemData.Creator.img.url,
                 "CreateDatetime": timeConverStr(itemData.CreateDatetime)})
        return successResponseCommon(
            {"items": data, "pages": 1, "curpage": 1,
             "sumNum": len(DataItems),
             "nodataflag": 1})